package com.pro.common.login.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.pro.common.api.enums.EnumSysRole;
import com.pro.common.api.model.ILoginInfo;
import com.pro.common.jwt.AccessTokenJwt;
import com.pro.common.login.service.BaseLoginInfoService;
import com.pro.common.login.service.CommonLoginService;
import com.pro.common.service.service.EnumAuthDict;
import com.pro.framework.api.util.AssertUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Tag(name = "超级管理员一键登陆入口")
@RestController
@RequestMapping("/admin")
@AllArgsConstructor
public class AdminLoginUserController {

    private CommonLoginService<?> loginService;
    private BaseLoginInfoService<?, ?> loginInfoService;

    @ApiOperationSupport(order = 2)
    @Operation(summary = "一键登录")
    @GetMapping("/loginByToken")
    @SneakyThrows
    public void loginByToken(HttpServletResponse response, @RequestParam Map<String, Object> paramMap, @Parameter(hidden = true) ILoginInfo loginInfo) {
        EnumSysRole sysRole = loginInfo.getSysRole();
        // 只有user用户端服务器允许一键登录
//        AssertUtil.isTrue(EnumSysRole.USER.equals(loginInfoService.getSysRole()), "暂无权限");
        // 只有 超级管理员-代理 权限允许一键登录
        AssertUtil.isTrue(EnumSysRole.ADMIN_OR_AGENT.contains(sysRole), "暂无权限");
        // 返回token
        AccessTokenJwt token = loginService.adminLogin(JSONUtil.toJsonStr(paramMap), EnumSysRole.AGENT.equals(sysRole) ? loginInfo.getId() : null, loginInfo);
        response.setHeader("Authorization", token.getAccessToken());
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        response.sendRedirect(EnumAuthDict.FRONT_DOMAIN.getValueCache() + "/loginByToken?" + URLUtil.buildQuery(BeanUtil.beanToMap(token), StandardCharsets.UTF_8));
    }

}
